#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Author:     feng minqiang  <wnfmq@126.com>
# Maintainer: feng minqiang  <wnfmq@126.com>

import web
import hashlib
import os,sys
import config
import logging
from web.contrib.template import render_jinja

render = render_jinja('templates/',encoding='utf-8')

#简单的测试一个字符串的MD5值
def GetStrMd5(src):
    m0=hashlib.md5()
    m0.update(src)
    print m0.hexdigest()
 
#大文件的MD5值
def GetFileMd5(filename):
    if not os.path.isfile(filename):
        return
    myhash = hashlib.md5()
    f = file(filename,'rb')
    while True:
        b = f.read(8096)
        if not b :
            break
        myhash.update(b)
    f.close()
    return myhash.hexdigest()
 
def CalcSha1(filepath):
    with open(filepath,'rb') as f:
        sha1obj = hashlib.sha1()
        sha1obj.update(f.read())
        hash = sha1obj.hexdigest()
        print(hash)
        return hash
 
def CalcMD5(filepath):
    with open(filepath,'rb') as f:
        md5obj = hashlib.md5()
        md5obj.update(f.read())
        hash = md5obj.hexdigest()
        #print(hash)
        return hash

def diff_md5_file(filepath,md5_str):
    _tmp_md5_str=CalcMD5(filepath)
    if _tmp_md5_str == md5_str:
        return True
    else:
        return False

def filelist(filepath=None,var_name=None):
    _fd=open(filepath)
    _buf=_fd.readlines()
    _fd.close()
    md5re={}
    for i in _buf:
        i=i.strip('\n').replace("  ",' ').split(' ')
        _md5_str=i[0]
        _file_name=i[1]
        if var_name!=None:
            _tmp_name=_file_name.split(".")[0]
            if _tmp_name != var_name:
                continue
        _file_path=os.path.join(os.path.dirname(filepath),_file_name)
        if not os.path.exists(_file_path):
            md5re.update({_file_name:False})
            continue
        _Re=diff_md5_file(_file_path,_md5_str)
        md5re.update({_file_name:_Re})
    return md5re

class md5sum:
    def GET(self):
        data=web.input()
        _version=None
        _var_name=None
        _len=len(data.items())
        for i in data.items():
            if i[0]=="PublicCloud":
                _version=i[1]
            if i[0]=="war":
                _var_name=i[1]
        if _version!=None:
            _path="/opt/download/PublicCloud/web/"+_version
            md5_file= _path + "/md5.txt"
            if not os.path.exists(md5_file):
                return None
            if _var_name!=None:
                return filelist(md5_file,_var_name)
            return filelist(md5_file)
class index:
    def GET(self):
        return True

if __name__ == "__main__":
    urls = ('/md5','md5sum',
            '/','index',
            )
    app=web.application(urls, globals())
    app.run()

